package com.bandit.controller;

import com.bandit.pojo.Blog;
import com.bandit.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {

    @Autowired
    private BlogService blogService;

    //首页跳转+查询
    @RequestMapping({"/toIndex","/"})
    public ModelAndView index(ModelAndView mv) throws Exception {
        int currentPage = 1;
        mv.addObject("pageInfo",blogService.getBlogByPage(currentPage));
        mv.addObject("blogList", blogService.getBlogByPage(currentPage).getBlogList());
        mv.setViewName("forward:/WEB-INF/jsp/show.jsp");
        return mv;
    }

    //首页查询
    @RequestMapping("/searchIndex")
    public ModelAndView searchIndex(HttpServletRequest request) throws Exception {
        String str = request.getParameter("str");
        System.out.println("[DEBUG]Search Input==>"+str);
        //查到所有相关博客id集合
        List<Integer> integerList = blogService.searchBlog(str);
        List<Blog> blogList= new ArrayList<>();
        for (Integer id : integerList) {
            Blog blogById = blogService.getBlogById(id);
            blogList.add(blogById);
        }
        ModelAndView mv = new ModelAndView();
        mv.addObject("searchInfo",str);
        mv.addObject("blogList", blogList);
        mv.setViewName("search");
        return mv;
    }

    @RequestMapping("/setPage")
    @ResponseBody
    public Map<String,Object> setPage(@RequestParam("currentPage") int currentPage){
        System.out.println("[DEBUG]current==>"+currentPage);
        //一个map保存后端查询值
        HashMap<String, Object> map = new HashMap<>();
        map.put("pageInfo",blogService.getBlogByPage(currentPage));
        map.put("blogList",blogService.getBlogByPage(currentPage).getBlogList());
        return map;
    }

    @RequestMapping("/toDetails")
    public ModelAndView toDetail(@RequestParam("id") int id){
        System.out.println("[DEBUG]id==>"+id);
        Blog blogById = blogService.getBlogById(id);
        blogService.updateClickHit(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("blogDetail",blogById);
        mv.setViewName("detail");
        return mv;
    }


}
